package org.meetunexpectedly.authority;

import org.meetunexpectedly.authority.verify.AuthorityVerify;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * @Description: 授权工具类
 * @Author: pupil
 * @Date: 2024/09/03 下午 5:52
 */
public class AuthorityUtils {

    /**
     * 用户权限集合
     * key: userId 用户id
     * value：权限集合
     */
    private static Map<Long, Collection<String>> userPermission = new HashMap<>();

    /**
     * 过滤权限集合
     */
    private static Set<String> filterPermission = new HashSet<>();

    /**
     * 全局权限校验类
     */
    private static Class clazz;

    /**
     * 是否开启全局校验 默认为false不开启
     */
    private static Boolean globalVerify = false;
    /**
     * /**
     * 是否开启 @PostMapping 全局校验 默认为false不开启
     */
    private static Boolean postAuthority = false;


    /**
     * 设置是否开启 @PostMapping 全局校验
     *
     * @param state 状态 false/true
     */
    public static void setPostAuthority(Boolean state, Class clz) {
        clazz = clz;
        postAuthority = state;
    }

    /**
     * 设置是否开启 全局校验
     *
     * @param state  状态 false/true
     * @param verify 校验
     */
    public static void setGlobalAuthority(Boolean state, Object verify) {
        if (verify == null) {
            throw new NullPointerException();
        } else if (!(verify instanceof AuthorityVerify)) {
            throw new ClassCastException(verify.getClass() + "类型不是 AuthorityVerify 实现类");
        }

        clazz = verify.getClass();
        globalVerify = state;
    }

    /**
     * 获取 GlobalVerify 状态
     *
     * @return
     */
    public static Boolean getGlobalVerifyState() {
        return globalVerify;
    }

    /**
     * 获取 postAuthority 状态
     *
     * @return
     */
    public static Boolean getPostAuthority() {
        return postAuthority;
    }


    /**
     * 重新初始化全局校验类Class
     */
    public static void cleanVerifyClass() {
        clazz = null;
    }


    /**
     * 获取全局权限校验类
     *
     * @return
     */
    public static Class getGlobalVerify() {
        return clazz;
    }


    /**
     * 校验权限
     *
     * @param userId     用户id
     * @param permission 权限
     * @return
     */
    public static Boolean verify(Long userId, String permission) {
        if (isEmpty(userId)) {
            return false;
        }

        // 校验用户是否存在该权限
        return userPermission.get(userId).contains(permission);
    }

    /**
     * 添加权限
     *
     * @param userId    用户id
     * @param authority 权限集合
     */
    public static void setAuthority(Long userId, Collection<String> authority) {
        userPermission.put(userId, authority);
    }


    /**
     * 用户权限是否为空
     *
     * @param userId 用户id
     * @return
     */
    public static Boolean isEmpty(Long userId) {
        return ObjectUtils.isEmpty(userPermission.get(userId));
    }
}
